<?php
namespace App\Http\Services;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;

/**
 * 一括送信
 * author: 吴镇曦
 */
class SendFile
{
    public function isCopyUpload ($userCompanyId, $path, $typeFile)
    {
        $serverKbn = config('businessVolume.SERVER_KBN');
        if ($serverKbn !== "0") {
            $awss3 = new AwsS3FilServer();
            $buf = $awss3->s3getFileMail($path);

            // 上传文件
            $filename1 = date('Ymd');
            $checkFile1 = '/temporaryFolder/' . $userCompanyId . '/' . $filename1 . '/' . $typeFile;
//            $newPath2 = 'app/public'.$checkFile1;

            $newPath2 = $checkFile1 . '/' .basename($path);
//            $res1 = storage_path($checkFile1);
//            if (!is_dir($res1)) {
//                mkdir($res1, 0777, true);
//                chmod($res1, 0777);
//            }
            Storage::disk('public')->put($newPath2, $buf);
            $path = $newPath2;
        }

        $realPath = realpath(public_path() . "/storage" . $path);
        if(!file_exists($realPath)){
            return;
        }
        // 上传文件
        $filename = date('Ymd');
        $need = '/' . $userCompanyId . '/';
        $checkFile = '/' . $userCompanyId . '/' . $filename . '/' . $typeFile;
        $newPath1 = 'app/public'.$checkFile;

        $newPath = $checkFile . '/' .basename($path);
        $res1 = storage_path($newPath1);
        if (!is_dir($res1)) {
            mkdir($res1, 0777, true);
            chmod($res1, 0777);
        }
        copy($realPath, $res1. '/' .basename($path));

        if ($serverKbn !== "0") {
//            return $path;
            $fileStore = $checkFile.'/' .basename($path);
//            return $fileStore;
            $awss3 = new AwsS3FilServer();
            $res = $awss3->s3pubFile($fileStore, $res1.'/'.basename($path));
            if ($res) {
                unlink($res1.'/'.basename($path));
                exec("rm -rf " . $res1);
            }
        }

        return $newPath;
    }
    public function gwCopyUpload ($request)
    {
        $id = $request->id;
        $userCompanyIdSelect = DB::table('contract_ready_info')->select('User_Company_id')->where('id', "$id")->first();
        $userCompanyId = $userCompanyIdSelect->User_Company_id;
        $typeFile = 'GWAddFiles';
        $originalName = $request['filename'];
        $ext = $request['fileExt'];
        $path = $request['filePath'];

        $serverKbn = config('businessVolume.SERVER_KBN');
        // SERVER_KBN=0 local
        if ($serverKbn !== "0") {
            $awss3 = new AwsS3FilServer();
            $buf = $awss3->s3getFileMail($path);

            // ファイルをアップロード
            $filename1 = date('Ymd');
            $checkFile1 = '/temporaryFolder/' . $userCompanyId . '/' . $filename1 . '/' . $typeFile;

            $newPath2 = $checkFile1 . '/' .basename($path);
            Storage::disk('public')->put($newPath2, $buf);
            $path = $newPath2;
        }
        // public_path函数はpublicファイルの絶対パスを戻る,realpath函数は絶対パス中の「././.」をフェルターする
        $realPath = realpath(public_path() . "/storage" . $path);
        // publicファイルのパスがない場合は直接戻ります
        if(!file_exists($realPath)){
            return;
        }
        // ファイルネームはYmdフォマートの時間を名付け
        $filename = date('Ymd');
        $checkFile = '/' . $userCompanyId . '/' . $filename . '/' . $typeFile;
        // 新たアップロードファイルPDFのパスを作成します
        $newPath1 = 'app/public'.$checkFile;
        //  パスのベ    ース名を取得します
        $newPath = $checkFile . '/' .basename($path);
        // storageファイルのしたで、$newPath1のファイル名を作成します
        $res1 = storage_path($newPath1);
        //  もし $res1 というファイルがない場合、作成します、最高の権限をあげる
        if (!is_dir($res1)) {
            mkdir($res1, 0777, true);
            chmod($res1, 0777);
        }
        // realPathのフォルダーはres1にコピーします
        copy($realPath, $res1. '/' .basename($path));

        if ($serverKbn !== "0") {
//            return $path;
            $fileStore = $checkFile.'/' .basename($path);
//            return $fileStore;
            $awss3 = new AwsS3FilServer();
            $res = $awss3->s3pubFile($fileStore, $res1.'/'.basename($path));
            if ($res) {
                unlink($res1.'/'.basename($path));
                exec("rm -rf " . $res1);
            }
        }

        $data = [];
        $data['clientOriginalName'] = $originalName;
        $data['ext'] = $ext;
        $data['realPath'] = $newPath;
        return $data;
    }

    public function iwCopyUpload ($request)
    {
        $id = $request->id;
        $userCompanyIdSelect = DB::table('contract_ready_info')->select('User_Company_id')->where('id', "$id")->first();
        $userCompanyId = $userCompanyIdSelect->User_Company_id;
        $typeFile = 'IWAddFiles';
        $originalName = $request['filename']; // 文件原名
        $ext = $request['fileExt'];  // 扩展名
        $path = $request['filePath']; // 文件路径
        $serverKbn = config('businessVolume.SERVER_KBN');
        if ($serverKbn !== "0") {
            $awss3 = new AwsS3FilServer();
            $buf = $awss3->s3getFileMail($path);

            // 上传文件
            $filename1 = date('Ymd');
            $checkFile1 = '/temporaryFolder/' . $userCompanyId . '/' . $filename1 . '/' . $typeFile;
//            $newPath2 = 'app/public'.$checkFile1;

            $newPath2 = $checkFile1 . '/' .basename($path);
//            $res1 = storage_path($checkFile1);
//            if (!is_dir($res1)) {
//                mkdir($res1, 0777, true);
//                chmod($res1, 0777);
//            }
            Storage::disk('public')->put($newPath2, $buf);
            $path = $newPath2;
        }
        $realPath = realpath(public_path() . "/storage" . $path);
        if(!file_exists($realPath)){
            return;
        }
        // 上传文件
        $filename = date('Ymd');
        $need = '/' . $userCompanyId . '/';
        $checkFile = '/' . $userCompanyId . '/' . $filename . '/' . $typeFile;
        $newPath1 = 'app/public'.$checkFile;

        $newPath = $checkFile . '/' .basename($path);
        $res1 = storage_path($newPath1);
//        $fileSize = filesize($res1);
        if (!is_dir($res1)) {
            mkdir($res1, 0777, true);
            chmod($res1, 0777);
        }
        copy($realPath, $res1. '/' .basename($path));

        if ($serverKbn !== "0") {
//            return $path;
            $fileStore = $checkFile.'/' .basename($path);
//            return $fileStore;
            $awss3 = new AwsS3FilServer();
            $res = $awss3->s3pubFile($fileStore, $res1.'/'.basename($path));
            if ($res) {
                unlink($res1.'/'.basename($path));
                exec("rm -rf " . $res1);
            }
        }

        $data = [];
        $data['clientOriginalName'] = $originalName;
        $data['ext'] = $ext;
        $data['realPath'] = $newPath;
//        $data['fileSize'] = $fileSize;
        return $data;
    }

    public function cwUpload ($request)
    {
        $file = $request->file('file');
        $id = $request->contractReadyInfoId;
        $userCompanyIdSelect = DB::table('contract_ready_info')->select('User_Company_id')->where('id', "$id")->first();
        $userCompanyId = $userCompanyIdSelect->User_Company_id;
        $typeFile = 'CWAddFiles';


        if ($file->isValid()) {
            $originalName = $file->getClientOriginalName(); // 文件原名
            $ext = $file->getClientOriginalExtension();   // 扩展名
            $realPath = $file->getRealPath();  //临时文件的绝对路径
            $type = $file->getClientMimeType();   // image/jpeg

            // 上传文件
            $filename = date('Ymd');
            // 使用我们新建的uploads本地存储空间（目录）
            $filename = 'public/' . $userCompanyId .'/' . $filename . '/' . $typeFile;
            $path = $file->store($filename);
            $res = config('app.url') . '/' . $path;
            $savePath = substr($res,23);
            $data = [];
            $data['clientOriginalName'] = $originalName;
            $data['ext'] = $ext;
            $data['realPath'] = $savePath;
            return $data;
        } else {
            return 'File not verified';
        }
    }

    /**
     * ファイルのサイズ
     * @param $allFile
     * @return mixed
     */
    public function allFileSize ($allFile) {
        if (!empty($allFile)) {
            for ($i = 0; $i < sizeof($allFile); $i++) {
                $path = $allFile[$i]['path'];
                $csvPath = $path;
                $serverKbn = config('businessVolume.SERVER_KBN');
                if ($serverKbn === '0') {
                    $path = realpath(public_path() . "/storage" . $path);
                    if (!$path) {
                        $path = realpath(public_path() . $csvPath);
                    }
                } else {
                    $awss3 = new AwsS3FilServer();
                    $buf = $awss3->s3getFile($path);
                    if (!$buf) {
                        $path = realpath(public_path() . "/storage" . $path);
                        if (!$path) {
                            $path = realpath(public_path() . $csvPath);
                        }
                    }
                }
                $fileSize = filesize($path);
                $MB = 1024 * 1024;
                $allFile[$i]['size'] = round($fileSize / $MB, 2);
            }
        }
        return $allFile;
    }

    /**
     * ファイルのサイズ
     * @param $allFile
     * @return mixed
     */
    public function oneFileSize ($path) {
        $serverKbn = config('businessVolume.SERVER_KBN');
        if ($serverKbn === '0') {
            $path = realpath(base_path('public/storage'.$path));
            $fileSize = filesize($path);
            $size = ceil($fileSize / 1024);
        } else {
            $awss3 = new AwsS3FilServer();
            $buf = $awss3->s3getFile($path);
//            $file = '/temporaryFolder'.$path;
            if (!$buf) {
                $path = realpath(base_path('public/storage'.$path));
                $fileSize = filesize($path);
                $size = ceil($fileSize / 1024);
            } else {
                $base64 = str_replace('=', '',$buf);
                $img_len = strlen($base64);
                $file_size = $img_len - ($img_len / 8) * 2;
                $size = ceil($file_size / 1024);
            }
        }
        return $size;
    }
}
